package com.marktotop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.marktotop.entity.business.Supplier;
import com.marktotop.entity.business.Vaccine;
import com.marktotop.entity.business.VaccineDevolution;
import com.marktotop.error.SystemCodeEnum;
import com.marktotop.error.SystemException;
import com.marktotop.mapper.VaccineDevolutionMapper;
import com.marktotop.response.ResultBean;
import com.marktotop.response.ResultCode;
import com.marktotop.service.IVaccineDevolutionService;
import com.marktotop.service.IVaccineService;
import com.marktotop.vo.business.SiteVaccineVO;
import com.marktotop.vo.business.VaccineDevolutionVO;
import com.marktotop.vo.business.VaccineVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author MarkToTop
 * @since 2021-07-16
 */
@Service
public class VaccineDevolutionServiceImpl extends ServiceImpl<VaccineDevolutionMapper, VaccineDevolution> implements IVaccineDevolutionService {

    @Autowired
    private VaccineDevolutionMapper devolutionMapper;

    @Autowired
    private IVaccineService vaccineService;

    /**
     * 疫苗下放列表记录，模糊分页展示
     *
     * @param pageNum
     * @param pageSize
     * @param devolutionVO
     * @return
     */
    @Override
    public ResultBean findVaccineDevolutionList(Integer pageNum, Integer pageSize, VaccineDevolutionVO devolutionVO) {
        // 开启分页
        Page<VaccineDevolutionVO> page = new Page<>(pageNum,pageSize);
        IPage<VaccineDevolutionVO> devolutionRecordByPage = devolutionMapper.getDevolutionRecordByPage(page,devolutionVO);
        if (devolutionRecordByPage.getRecords().isEmpty()){
            return ResultBean.result(ResultCode.NON_RESULT);
        }
        return ResultBean.ok().message("获取所有疫苗下发记录信息成功！")
                .data("total",devolutionRecordByPage.getTotal())
                .data("devolutRecordList",devolutionRecordByPage.getRecords());
    }


    /**
     * 添加疫苗下发记录信息
     *
     * @param devolution
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addVaccineDevolutionRecord(VaccineDevolution devolution) throws SystemException {
        VaccineVO vaccineInfo = vaccineService.getVaccineInfo(devolution.getVaccineId());
        if (null == vaccineInfo){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"要添加的下放记录中疫苗信息不存在!");
        }
        // 保证疫苗的剩余量大于0，并大于下发数量
        if (vaccineInfo.getOverage() > 0){
            if (devolution.getDeCount() <= vaccineInfo.getOverage() ){
                // 修改疫苗的剩余量 (减去 疫苗的下发数)
                if (!vaccineService.editOverage(vaccineInfo, devolution.getDeCount())){
                    throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"修改疫苗库存操作失败!");
                }
                // 添加中间表记录 - 没有的话添加，有记录的话修改库存
                SiteVaccineVO recordFormSite = devolutionMapper.getRecordFormSite(devolution.getVaccineSiteId(), devolution.getVaccineId());
                if (recordFormSite == null){
                    // 添加中间表数据
                    devolutionMapper.insertOrderToSite(devolution);
                } else {
                    int newCount = recordFormSite.getCount() + devolution.getDeCount();
                    recordFormSite.setCount(newCount);
                    // 更新 中间表库存数据
                    devolutionMapper.updateCountRecord(recordFormSite);
                }
                // 设置当前下放时间、接种点疫苗数 - 写入下发表
                devolution.setCreateTime(new Date());
                if (0 == devolutionMapper.insert(devolution)){
                    throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"添加下发记录操作失败!");
                }
                return true;
            }
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"疫苗库存数不足，无法下放至接种点!");
        }
        throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"该疫苗库存数为0，请查证后下发!");
    }


    /**
     * 编辑 疫苗下发记录
     *
     * @param id
     * @return
     */
    @Override
    public VaccineDevolutionVO editDevolutionRecord(Long id) {
        return devolutionMapper.getDevolutionRecordById(id);
    }


    /**
     * 只要该接种点有疫苗记录返回true，如果有，查询所有疫苗库存是否都为0
     *          中间表查询
     * @param id
     * @return
     */
    @Override
    public boolean haveRecordsBySiteId(Long id) {
        List<SiteVaccineVO> devolutions = devolutionMapper.selectRecordsBySiteId(id);
        if (devolutions.isEmpty()){
            return false;
        }
        // 判断该接种点的所有疫苗库存是否都为0
        for (SiteVaccineVO devolution : devolutions) {
            if (devolution.getCount() != 0){
                return true;
            }
        }
        return true;
    }


}
